package eu.connect.im;

import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.protocol.HTTP;


public class HTTPClientProxyThread extends Thread implements Partner
{
	private HttpRequest request;
	private HttpResponse response;
	private MessageQueue queue;
	private Object lock;
	private Partner correpondingPartner;
	
	
	public HTTPClientProxyThread(HttpRequest request, HttpResponse response, MessageQueue queue)
	{
		super();
		this.request = request;
		this.response = response;
		this.queue = queue;
		lock = new Object();
	}
	
	public void run()
	{
		if (request instanceof HttpEntityEnclosingRequest)
		{			
			request.removeHeaders(HTTP.CONTENT_LEN);
            request.removeHeaders(HTTP.TRANSFER_ENCODING);
            request.removeHeaders(HTTP.CONN_DIRECTIVE);
            request.removeHeaders("Keep-Alive");
            request.removeHeaders("Proxy-Authenticate");
            request.removeHeaders("TE");
            request.removeHeaders("Trailers");
            request.removeHeaders("Upgrade");
			
			Message msg = new Message(request, "HttpRequest", "client");
			msg.setMyrole(this);
			msg.setYourrole(this.correpondingPartner);
			queue.addMessage(msg);
			
			synchronized (lock)
			{
				try {
					lock.wait();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			return;
		}
		else
		{
			response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
		}
	}
	
	public void setCorrepondingPartner(Partner correpondingPartner)
	{
		this.correpondingPartner = correpondingPartner;
	}
	
	@Override
	public void sendMessage(Message msg)
	{
		// TODO Auto-generated method stub
		HttpResponse targetResponse = (HttpResponse)msg.getMessageEntity();
		this.response.setStatusLine(targetResponse.getStatusLine());
        this.response.setHeaders(targetResponse.getAllHeaders());
        this.response.setEntity(targetResponse.getEntity());
        synchronized (this.lock)
        {
        	this.lock.notifyAll();
        }
	}

}
